//
//  NetworkTool.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/7/12.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "NetworkTool.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NetworkTool

+(instancetype)sharedTools{
    
    //  https://www.findif.cn/  正式环境
   // https://webapp.hiwan.net.cn/  测试环境
    
    static NetworkTool *instance;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        //基本的地址
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        NSURL *url = [NSURL URLWithString:@"https://www.findif.cn/"];
        
        instance = [[NetworkTool alloc] initWithBaseURL:url sessionConfiguration:config];
        
        //设置超时时间
        config.timeoutIntervalForRequest = 10;
       
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream",@"text/xml", nil];
        instance.requestSerializer = [AFHTTPRequestSerializer serializer];
        
    });
    return instance;
}

#pragma mark - 基础
//- (void)requestWithType:(RequestType)type andUrl:(NSString *)url andParameters:(NSMutableDictionary*)params andTimeOut:(double)timeOut resultWithBlock:(result)finishBlock
//{
//
//    if(!url || [url length] == 0)
//    {//如果传入的url为空,这时候
//        finishBlock(NO,@"请求地址不能为空");
//        return;
//    }
//
//    //设置超时时间
//    self.requestSerializer.timeoutInterval = timeOut;
//    //拼接URL
//    NSString *urlStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,url];
//    NSLog(@"url%@",urlStr);
//
//
//    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:ZSToken];
//    if(token.length != 0 && ![url isEqualToString:@"/index/Nanjinliuhe/getService"] && ![url isEqualToString:@"/index/Nanjinliuhe/getSerDet"]){
//        params[@"token"] = token;
//    }
//
//
//    NSLog(@"请求参数%@",params);
//
//    if (type == GET) {
//        _requestTask = [self.manager GET:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//            finishBlock(YES,responseObject);
//
//
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//            finishBlock(NO, @"");
//            NSLog(@"网络错误信息：%@",error);
//
//        }];
//
//    } else {
//
//        if (params == nil)
//        {
//            finishBlock(NO,@"post请求->请传入参数");
//            return;
//        }
//
//        _requestTask = [self.manager POST:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//            finishBlock(YES, responseObject);
//
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//            finishBlock(NO, @"");
//            NSLog(@"网络错误信息：%@",error);
//        }];
//
//    }
//
//}


#pragma mark - 新闻详情接口
- (void)sendMsgWithPhone:(NSString *)phone resultWithBlock:(result)finishBlock{
    
    //获取当前时间日期
    NSDate *date=[NSDate date];
    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr;
    dateStr=[format1 stringFromDate:date];
    
    NSDictionary * dict = @{@"phone":phone,@"templId":@"105642",@"timeStamp":dateStr};
    
    NSString * sign = [self signStr:dict];
    
    NSDictionary * resDict = @{@"phone":phone,@"templId":@"105642",@"timeStamp":dateStr,@"sign":sign};
    
    [self POST:@"Api/sendMsg" parameters:resDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        int code = [responseObject[@"code"] intValue];
        
        if (code == 200) {
            
            finishBlock(YES,responseObject);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
















- (NSString *)signStr:(NSDictionary *)dict{
    
    NSArray *keyArray = [dict allKeys];
    
    //定义一个排序数组，存储排序好之后的key值
    NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    //这时我们再创建一个数组，来按升序存储key对应的Value，通过遍历sortArray的方法
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortString in sortArray) {
        [valueArray addObject:[dict objectForKey:sortString]];
    }
    //    现在我们有两个数组，分别对应升序排序的key和value，所以再创建一个keyValue的数组来存储每一个key和value的格式
    //    NSMutableArray *signArray = [NSMutableArray array];
    //    for (int i = 0; i < sortArray.count; i++) {
    //        NSString *keyValueStr = [NSString stringWithFormat:@"%@:%@",sortArray[i],valueArray[i]];
    //        [signArray addObject:keyValueStr];
    //    }
    
    //最后的一步，就是用“,”把每个字符串拼接起来
    NSString *sign = [valueArray componentsJoinedByString:@""];
    
    NSString * resStr = [NSString stringWithFormat:@"%@NDQ0NTlmMDk4MTU3NTg3NzFiZTFlZmQwNDFjNzA0ZGMyYWY0NzU5ZQ==",sign];
    
    NSString *signStr = [self md5:resStr];
    
    NSString * baseStr = [self encode:signStr];
    
    return baseStr;
}

- (NSString *) md5:(NSString *) str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (NSString *)encode:(NSString *)string
{
    //先将string转换成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    
    return baseString;
}



@end
